#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
use XML::TreeBuilder;
use File::Copy;

my $ARGC = $#ARGV + 1;

my $outF = "./outputs/";
my $handCheckedF = "./handChecked/";
my $toCheckF = "./toCheck/";
my $tempName = "test.ic";

if($ARGC < 1) {
	print "Usage: $0 <test case file> [<add main: 0|1> (default: 0)]\n";
	exit(0);
}

my $tree = XML::TreeBuilder->new();
my $i = 0;
my $mainStr = "";
if(($ARGC > 1) && ($ARGV[1] == "1")) {
	$mainStr = "\nclass Main { static void main(string[] args) {   } }\n\n";
}
$tree->parse_file($ARGV[0]);
$collections = $tree->find_by_tag_name('collections');
foreach my $cases ($collections) {
	
	foreach my $testCase ($cases->find_by_tag_name('testCase')) {
		$isAllowed = $testCase->attr_get_i('allowed');
		$name = $testCase->attr_get_i('name');
		@content = $testCase->content_list;
		
		$outFilename = $outF . $name ."_" .$isAllowed. ".ic";
		$toCheckFilename = $toCheckF . $name. "_". $isAllowed . ".ic";
		$handCheckedFilename = $handCheckedF . $name . "_" . $isAllowed . ".ic";
		
		$fullTxt = $mainStr . $content[0];
		open(FILEWRITE, "> $tempName");
        print FILEWRITE $fullTxt;
	
		if($isAllowed =~ m/true/) {
			# generate compiler output to $outFilename
			system("/home/mic/.eclipse/ic-compiler/run '$tempName -L ../ic/libic.sig -dump-code' >$outFilename 2>&1");
		
			# read compiler output from $outFilename
			local $/;
			open(FILEREAD, "< $outFilename");
			$data = <FILEREAD>; 
			close(FILEREAD);
			
			if($data =~ m/incorrect|error|No argument is given/) {
				print "=== Test '$name' (allowed=$isAllowed)  FAILED ===\n";
				# print "Output Dump:\n";
				# print $data;
				print "Please see: $outFilename\n\n";
			}
			else {
				if(-e $handCheckedFilename) {
#					print $outFilename."\n";
#					print $handCheckedFilename."\n";
#					open(FILEREAD, "< $handCheckedFilename");
#					$HandData = <FILEREAD>;
#					close(FILEREAD);
					my $diff = `diff $handCheckedFilename $outFilename`;
					if($diff) {
						print "=== Test '$name' (allowed=$isAllowed) FAILED ===\n";
						print "Please see: $outFilename\n\n";
						print "";
					}
					else {
						print "=== Test '$name' (allowed=$isAllowed) Passed ===\n\n";
					}
				}
				else {
					copy($outFilename, $toCheckFilename);
					print "Please check this test manually @ $toCheckFilename\nIf it is Ok then transfer it to $handCheckedF\n\n";
				}
			}
			$i++;
		}
		else {  # not allowed
			system("/home/mic/.eclipse/ic-compiler/run '$tempName -L ../ic/libic.sig -dump-code' >$outFilename 2>&1");
			
			local $/;
			open(FILEREAD, "< $outFilename");
			$data = <FILEREAD>;
			close(FILEREAD);
		
			if($data =~ m/incorrect|error/) {
				print "=== Test '$name' (allowed=$isAllowed) Passed ===\n\n";
			}
			else {
				print "=== Test '$name' (allowed=$isAllowed) FAILED ===\n";
				print "Output Dump:\n";
				print $data;
				print "\n\n";
				print "Please see: $outFilename\n\n";
			}
		}
	}
}

